<script setup lang="ts">
import { reactive, ref } from 'vue';
import { message } from "ant-design-vue";
import router from "@/router";
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons-vue';
import { userRegister } from "@/api/userController.ts";

const loading = ref(false);

interface RegisterForm {
  userAccount: string;
  userPassword: string;
  checkPassword: string;
  userName?: string;
  userProfile?: string;
}

const formState = reactive<RegisterForm>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  userName: '',
  userProfile: ''
});

const rules = {
  userAccount: [
    { required: true, message: '请输入账号!', trigger: 'blur' },
    { min: 4, max: 16, message: '账号长度需在4-16个字符之间', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码!', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  checkPassword: [
    { 
      required: true, 
      message: '请确认密码!', 
      trigger: 'blur' 
    },
    { 
      validator: (rule: any, value: string) => {
        if (value === '') {
          return Promise.reject('请确认密码');
        } else if (value !== formState.userPassword) {
          return Promise.reject('两次输入的密码不一致');
        }
        return Promise.resolve();
      }, 
      trigger: 'blur' 
    }
  ],
  userName: [
    { max: 16, message: '用户名长度不超过16个字符', trigger: 'blur' }
  ]
};

const onFinish = async () => {
  loading.value = true;
  try {
    const res = await userRegister({
      userAccount: formState.userAccount,
      userPassword: formState.userPassword,
      checkPassword: formState.checkPassword,
      userName: formState.userName,
      userProfile: formState.userProfile
    });
    
    if (res.data.code === 0) {
      message.success('注册成功');
      router.push('/user/login');
    } else {
      message.error('注册失败：' + res.data.message);
    }
  } catch (error) {
    message.error('注册请求失败，请稍后再试');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
</script>

<template>
  <div class="register-container">
    <a-card class="register-card" :bordered="false">
      <template #title>
        <div class="register-title">
          <span class="title-icon"><UserOutlined /></span>
          用户注册
        </div>
      </template>
      <a-form
        :model="formState"
        name="register"
        :rules="rules"
        :label-col="{ span: 0 }"
        :wrapper-col="{ span: 24 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        class="register-form"
      >
        <a-form-item name="userAccount">
          <a-input 
            v-model="formState.userAccount"
            size="large"
            placeholder="请输入账号（4-16位）"
          >
            <template #prefix><UserOutlined style="color: rgba(0,0,0,.25)" /></template>
          </a-input>
        </a-form-item>

        <a-form-item name="userPassword">
          <a-input-password
            v-model="formState.userPassword"
            size="large"
            placeholder="请输入密码（至少6位）"
          >
            <template #prefix><LockOutlined style="color: rgba(0,0,0,.25)" /></template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="checkPassword">
          <a-input-password
            v-model="formState.checkPassword"
            size="large"
            placeholder="请确认密码"
          >
            <template #prefix><LockOutlined style="color: rgba(0,0,0,.25)" /></template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="userName">
          <a-input 
            v-model="formState.userName"
            size="large"
            placeholder="请输入用户名（选填）"
          >
            <template #prefix><UserOutlined style="color: rgba(0,0,0,.25)" /></template>
          </a-input>
        </a-form-item>

        <a-form-item name="userProfile">
          <a-textarea
            v-model="formState.userProfile"
            placeholder="请输入个人简介（选填）"
            :rows="4"
          />
        </a-form-item>

        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit" 
            block 
            size="large"
            :loading="loading"
          >
            注册
          </a-button>
        </a-form-item>
        
        <div class="form-footer">
          <a-button type="link" @click="router.push('/user/login')">
            已有账号？立即登录
          </a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.register-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.title-icon {
  margin-right: 12px;
  font-size: 28px;
}

.register-form {
  padding: 10px 0;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>
